package com.adresvseti.wallpaperoid.services;

import com.adresvseti.wallpaperoid.utils.BitmapUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;

/**
 * Decodes and resizes bitmap.
 *
 */
public class DecodeResourceBitmapTask extends AsyncTask<Integer, Void, Bitmap> {

	private final Context context;
	private final int targetWidth;
	private final int targetHeight;
	private final IDecodeBitmapCallback callback;
	
    private Bitmap result;
    

    public DecodeResourceBitmapTask(Context context, int targetWidth, int targetHeight, IDecodeBitmapCallback callback) {
        
    	this.context = context;
    	this.targetWidth = targetWidth;
    	this.targetHeight = targetHeight;
    	this.callback = callback;
    }

    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        int resId = params[0];
        
        // First decode with inJustDecodeBounds=true to check dimensions
		final Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(context.getResources(), resId, options);

		// Calculate inSampleSize
		options.inSampleSize = BitmapUtil.calculateInSampleSize(options, targetWidth, targetHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		result = BitmapFactory.decodeResource(context.getResources(), resId, options);

		return result;
    }

    // Once complete, see if ImageView is still around and set bitmap.
    @Override
    protected void onPostExecute(Bitmap bitmap) {
    	
    	callback.success(bitmap);
    	
    }
	
}
